package com.faxsun.web.controller.user;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.faxsun.core.service.LiveAdminService;
import com.faxsun.core.service.UserService;
import com.faxsun.pojos.view.Live;
import com.faxsun.web.controller.FrontViewConstants;
import com.faxsun.web.pojos.FSUserProfile;

import mblog.core.pojos.User;
import mblog.web.controller.BaseController;
import mtons.modules.pojos.UserContextHolder;
import mtons.modules.pojos.UserProfile;

@Controller
@RequestMapping("/users")
public class LiveCenterController extends BaseController {

	@Autowired
	protected UserService userService;

	@Autowired
	protected LiveAdminService liveAdminService;

	@RequestMapping(value = "/live/{userId}", method = RequestMethod.GET)
	public String getCenter(@PathVariable Long userId, ModelMap model, HttpServletRequest request) {

		if (!userValid(userId)) {
			return FrontViewConstants.VIEW_404;
		}

		model.addAttribute("userId", userId);

		UserProfile up = UserContextHolder.getUserProfile();

		boolean authorized = this.authorized(userId);
		if (authorized) {
			// 用户本人访问
			model.addAttribute("authorized", "true");
			List<Live> lives = liveAdminService.getMyLiveWithNop(up.getId());
			if (lives == null) {
				lives = Collections.emptyList();
			}
			model.addAttribute("lives", this.binningLives(lives));
		} else {
			// return "redirect:/";
			model.addAttribute("authorized", "false");

			User u = userService.get(userId.longValue());
			up = new FSUserProfile(u.getId(), u.getUsername());
			up.setAvatar(u.getAvatar());
			up.setLastLogin(u.getLastLogin());
			up.setEmail(u.getEmail());
			up.setName(u.getName());
			((FSUserProfile) up).setSignature(u.getSignature());
		}
		model.addAttribute("profile", up);

		model.addAttribute("hintAvatar", up.getAvatar().contains("head") ? "true" : "false");
		return FrontViewConstants.VIEW_USER_CENTER;
	}

	private boolean userValid(Long userId) {
		User u = userService.get(userId.longValue());
		if (u == null) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * check if current user has required permission for action like update
	 * avatar/name
	 * 
	 * @param userId
	 *            the user id upon which action is taken
	 * @return true if authorization ok otherwise false
	 */
	private boolean authorized(Long userId) {
		UserProfile up = UserContextHolder.getUserProfile();
		if (up == null || up.getId() < 1 || up.getId() != userId.longValue()) {
			return false;
		} else {
			return true;
		}
	}

	private HashMap<String, List<Live>> binningLives(List<Live> lives) {
		LinkedHashMap<String, List<Live>> binning = new LinkedHashMap<String, List<Live>>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Collections.sort(lives, new Comparator<Live>() {
			@Override
			public int compare(Live o1, Live o2) {
				if (o1.getStartTime().getTime() > o2.getStartTime().getTime()) {
					return -1;
				}
				if (o1.getStartTime().getTime() > o2.getStartTime().getTime()) {
					return 1;
				} else {
					return 0;
				}
			}

		});
		for (Live live : lives) {
			Date startDate = live.getStartTime();
			String dateStr = sdf.format(startDate);
			List<Live> dayLives = binning.get(dateStr);
			if (dayLives == null) {
				dayLives = new ArrayList<Live>();
				binning.put(dateStr, dayLives);
			}
			dayLives.add(live);
		}

		return binning;
	}
}
